#include "repairwidget.h"           // 设备维修
#include "ui_repairwidget.h"
#include"src/mes.h"
#include<QMessageBox>
#include<QSqlTableModel>
#include<QFileDialog>
#include<QTextStream>
#include<QFile>
#include<QMenu>
#include<QClipboard>

RepairWidget::RepairWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RepairWidget)
{
    ui->setupUi(this);
    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));

    initTableView(QStringList());
}

RepairWidget::~RepairWidget()
{
    delete ui;
}

void RepairWidget::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void RepairWidget::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}

void RepairWidget::on_pushButton_clicked()
{
    QString NO=ui->NO->text().trimmed();
    QString workNumber=ui->workNumber->text().trimmed();
    QString textReason=ui->textEdit->toPlainText();
    if(NO=="" || workNumber=="" || textReason.trimmed()==""){
        ui->msgError->setText("带*号项目不能为空");
        return;
    }

    int useAccount;
    if(!Mes::getInstance()->NOworkNumberIsExist(NO,workNumber,useAccount)){
        ui->msgError->setText(QString("该保管人所拥有的设备(%1)不存在").arg(NO));
        return;
    }

    if(useAccount==0){
        ui->msgError->setText("当前设备数量已为0");
        return;
    }

    if(Mes::getInstance()->insertUpdateRepairForm(NO,workNumber,textReason)){
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
    }
}

void RepairWidget::initTableView(QStringList sqlist)
{
    RepairTable *model=new RepairTable(this);
    model->setSqlist(sqlist);

    model->setTable("repairForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setHeaderData(0,Qt::Horizontal,tr("勾选设备"));
    model->setHeaderData(1,Qt::Horizontal,tr("设备编号"));
    model->setHeaderData(2,Qt::Horizontal,tr("报修人工号"));
    model->setHeaderData(3,Qt::Horizontal,tr("维修原因"));
    model->setHeaderData(4,Qt::Horizontal,tr("维修时间"));
    model->setHeaderData(5,Qt::Horizontal,tr("维修状态"));
    model->setHeaderData(6,Qt::Horizontal,tr("维修前模式"));
//    model->setHeaderData(7,Qt::Horizontal,tr("使用人工号"));
    model->select();
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
}


RepairTable::RepairTable(QObject *parent, QSqlDatabase db)
{

}

bool RepairTable::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;


    if (role == Qt::CheckStateRole && index.column() == checkColumn)
    {
        check_state_map.clear();
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);return true;
    }
    else
        return QSqlTableModel::setData(index, value,role);
}

QVariant RepairTable::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.column() != checkColumn )
    {
        return QSqlTableModel::data(index, role);
    }
    switch(role)
    {
        case Qt::CheckStateRole:
        if(index.column() == checkColumn)
        {
            if (check_state_map.contains(index.row()))
            {
//                qDebug()<<"data";
                return Qt::Checked;
//                return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
            }

            return Qt::Unchecked;
        }
        default:
            return QVariant();
    }
    return QVariant();
}

Qt::ItemFlags RepairTable::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;
    if (index.column() == checkColumn)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
    else
        return QSqlTableModel::flags(index);
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QString RepairTable::selectStatement() const
{
    QString condition="where status='维修中'";
    for(QString tmp:sqlist){
        if(tmp==NULL){
            continue;
        }
        condition+=QString(" and ")+tmp;
    }

    QString sql=QString("SELECT TOP 200 [status],[NO]    \
                        ,[workNumber]   \
                        ,[textReason]   \
                        ,[date] \
                        ,[status]   \
                        ,[modelStr] \
                    FROM [dm-data].[dbo].[repairForm] %1").arg(condition);
//    ,[userNumber]
    return sql;
}

void RepairWidget::on_pushButton_3_clicked()
{
    RepairTable *model=dynamic_cast<RepairTable *>(ui->tableView->model());
    auto i=model->check_state_map.begin();
    if(i==model->check_state_map.end()){
        ui->msgVer->setText("所选设备不能为空");
        ui->msgVer->setFocus();
        return;
    }
    QString remarks=ui->remarks->toPlainText();
    if(remarks.trimmed()==""){
        ui->msgVer->setText("带*号项目不能为空");
        return;
    }
    QModelIndex modelIndexNO=model->index(i.key(),1,QModelIndex());
    QModelIndex modelIndexModelStr=model->index(i.key(),6,QModelIndex());
    QModelIndex modelIndexUserNumber=model->index(i.key(),2,QModelIndex());
    QString NO=modelIndexNO.data().toString();
    QString modelStr=modelIndexModelStr.data().toString();
    QString userNumber=modelIndexUserNumber.data().toString();
    if(Mes::getInstance()->repairVer(NO,remarks,modelStr,userNumber)){
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
        on_refreshButton_clicked();
    }
}

void RepairWidget::on_exportButton_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView->model()->rowCount();
        int columns = ui->tableView->model()->columnCount();
        for(int j=1;j<columns;j++){
            if(j==3) continue;
            textData+=ui->tableView->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 1; j < columns; j++){
                    if(j==3) continue;
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString().replace(",",";");
                    textData += "," ;     // for .csv file format
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void RepairWidget::on_refreshButton_clicked()
{
    initTableView(QStringList());
}

void RepairWidget::on_workNumber_textEdited(const QString &arg1)
{
    QString newName;
    if(Mes::getInstance()->getName(arg1,newName)){
        ui->nameLabel->setText(newName);
    }else{
        ui->nameLabel->setText("工号不存在");
    }
}
